package controllers

import (
	"accx/appFramework/m_config"
	"accx/models/sync"
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"net/http"
)

func SyncDataFromUDMTo(c *gin.Context) {

}

func AccxUdmDynamicData(c *gin.Context) {
	code := http.StatusOK
	respMsg := sync.ResponseSucMsg{Code: 200}
	var Servers []sync.Service
	var reqData sync.DynamicData
	err := c.ShouldBindJSON(&reqData)
	if err != nil {
		seelog.Error("failed to get request data: ", err)
		code = http.StatusGatewayTimeout
		respMsg.Code = code
		respMsg.Message = "Accx timeout"
		goto END
	}
	//TODO 读取得到连接的各个随遇模块信息
	for _, v := range m_config.AccxAndAllaccxData.Accx {
		if v.Status == m_config.Connect {
			Servers = append(Servers, sync.Service{
				IP:   v.ServiceIp,
				Port: 2444,
			})
		}
	}

	//TODO 将数据同步广播给各个随遇模块
	respMsg.Data, err = reqData.BroadcastRequest(Servers)
	if err != nil {
		code = http.StatusGatewayTimeout
		respMsg.Code = code
		respMsg.Message = "Accx timeout"
		goto END
	}
END:
	c.JSON(code, respMsg)
}

func AccxDynamicData(c *gin.Context) {
	code := http.StatusOK
	respMsg := sync.ResponseSucMsg{Code: 200}
	var reqData sync.DynamicData
	err := c.ShouldBindJSON(&reqData)
	if err != nil {
		seelog.Error("add reqData: ", err)
		code = http.StatusNotImplemented
		respMsg.Code = code
		respMsg.Message = err.Error()
		goto END
	}
	//TODO 将数据同步给本端的UDM
	err = reqData.SendUDM()
	if err != nil {
		code = http.StatusNotImplemented
		respMsg.Code = code
		respMsg.Message = "Not implemented"
		goto END
	}
END:
	c.JSON(code, respMsg)
}
